<template>
    <div class="table-form-page">
        <div class="form-page-header">
            <div>
                <el-page-header @back="closeWindow" content="仪器维修申请" />
            </div>
            <div>
                <el-button v-show="showSaveBtn" @click="chooseDevice">选择仪器</el-button>
                <el-button v-show="showSaveBtn" @click="uploadPic">上传附件</el-button>
                <el-button v-show="showSaveBtn" type="primary" @click="onSubmit">保存</el-button>
                <el-button v-show="showReviewBtn" type="primary" @click="onReview">审批</el-button>
                <el-button type="default" @click="onPrint">打印</el-button>
                <input ref="fileInput" type="file" accept="image/*" style="display: none" @change="onFileChange" />
            </div>
        </div>
        <div class="form-content">
            <table class="table-class" border="0" cellspacing="0" cellpadding="0">
                <col class="label-col" />
                <col class="content-col" />
                <col class="label-col" />
                <col class="content-col" />
                <tr class="tr-class">
                    <td class="tab-class" colspan="4">申请信息</td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class print-label">项目名称</td>
                    <td class="td-class content-class" colspan="3">
                        <el-input
                            v-model="form.projectName"
                            class="form-input-class"
                            placeholder="请选择"
                            readonly
                            @click="chooseProject"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class print-label">需维修仪器</td>
                    <td class="td-class" colspan="3">
                        <el-table ref="datagrid" :data="form.deviceData" border>
                            <el-table-column prop="code" label="仪器编号" />
                            <el-table-column prop="name" label="仪器名称" />
                            <el-table-column prop="model" label="仪器型号" />
                        </el-table>
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class print-label">损坏情况</td>
                    <td class="td-class" colspan="3">
                        <el-input
                            v-model="form.damageCondition"
                            type="textarea"
                            class="form-input-class"
                            :rows="3"
                            placeholder="请输入仪器损坏情况"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class print-label">损坏原因</td>
                    <td class="td-class" colspan="3">
                        <el-input
                            v-model="form.damageReason"
                            type="textarea"
                            class="form-input-class"
                            :rows="3"
                            placeholder="请输入仪器损坏原因"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class print-label">仪器所在地</td>
                    <td class="td-class" colspan="3">
                        <el-input
                            v-model="form.deviceAddress"
                            type="textarea"
                            class="form-input-class"
                            :rows="3"
                            placeholder="请输入仪器所在地"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class print-label">设备维修报价</td>
                    <td class="td-class content-class" colspan="3">
                        <el-input
                            v-model="form.maintainPrice"
                            class="form-input-class"
                            placeholder="请输入设备维修报价"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class print-label">图片</td>
                    <td class="td-class" colspan="3">
                        <div class="attachment-content">
                            <div v-for="item in picUrls" class="attachment-box">
                                <img :src="item" class="attachment-class" @click="previewFile(item)" />
                            </div>
                        </div>
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class print-label">备注</td>
                    <td class="td-class" colspan="3">
                        <el-input
                            v-model="form.remark"
                            type="textarea"
                            class="form-input-class"
                            :rows="5"
                            placeholder="请输入备注"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="tab-class" colspan="4">审批流程</td>
                </tr>
                <tr id="maintainIgnore2" class="tr-class">
                    <td class="td-class" colspan="4">
                        <FlowCpt
                            ref="processRef"
                            :flowType="form.flowTypeCode"
                            :disabled="!showSaveBtn"
                            :taskId="id"
                        ></FlowCpt>
                        <FlowOperationCpt
                            v-if="showReviewDialog"
                            :data="form"
                            @close="closeReviewDialog"
                        ></FlowOperationCpt>
                    </td>
                </tr>
                <tr class="tr-class" v-if="showFlowHis">
                    <td class="tab-class" colspan="4">审批记录</td>
                </tr>
                <tr class="tr-class" v-if="showFlowHis">
                    <td class="td-class" colspan="4">
                        <FlowHistoryCpt :taskId="id" />
                    </td>
                </tr>
            </table>
        </div>
        <el-dialog
            width="800px"
            top="20vh"
            title="设备"
            v-model="showDevice"
            :lock-scroll="true"
            :close-on-click-modal="false"
        >
            <div class="dialog-content">
                <DeviceGrid :single="false" @select="deviceSelected"></DeviceGrid>
            </div>
        </el-dialog>
        <el-dialog
            width="800px"
            top="10vh"
            title="项目"
            v-model="showProjectGridCpt"
            :lock-scroll="true"
            :close-on-click-modal="false"
        >
            <div class="dialog-content">
                <ProjectGridCpt @select="projectSelected"></ProjectGridCpt>
            </div>
        </el-dialog>
        <el-dialog
            width="840px"
            top="10vh"
            title="打印预览"
            v-model="showPrint"
            :lock-scroll="true"
            :close-on-click-modal="false"
            :destroy-on-close="true"
        >
            <PrintTemplate :id="form.id"></PrintTemplate>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElNotification } from 'element-plus'
import http from '@/http.js'
import DeviceGrid from './DeviceGrid.vue'
import ProjectGridCpt from '@/components/pub/ProjectGridCpt.vue'
import PrintTemplate from '@/print/yunying/DeviceMaintainPrint.vue'
import FlowCpt from '@/components/process/FlowCpt.vue'
import FlowOperationCpt from '@/components/process/FlowOperationCpt.vue'
import FlowHistoryCpt from '@/components/process/FlowHistoryCpt.vue'

const props = defineProps({
    id: {
        type: String,
        default: ''
    }
})

const emit = defineEmits(['close'])

const processRef = ref(null)
const fileInput = ref(null)

const form = reactive({
    id: '',
    projectId: '',
    projectCode: '',
    projectName: '',
    deviceData: [],
    devices: '',
    damageCondition: '',
    damageReason: '',
    deviceAddress: '',
    maintainPrice: '',
    pics: '',
    remark: '',
    flowTypeCode: 'DEVICE_MAINTAIN',
    processData: []
})

const picUrls = ref([])

const showDevice = ref(false)
const showProjectGridCpt = ref(false)
const showSaveBtn = ref(false)
const showReviewBtn = ref(false)
const showReviewDialog = ref(false)
const showFlowHis = ref(false)
const showPrint = ref(false)

const closeWindow = () => {
    emit('close')
}

const loadDetail = () => {
    http.fetchForm({
        url: '/yunying/deviceMaintain/findById',
        method: 'get',
        data: {
            id: props.id
        }
    }).then((res) => {
        let data = res.data
        data['deviceData'] = JSON.parse(data.devices)
        Object.assign(form, data)

        let pics = data.pics
        if (pics != '') {
            let list = pics.split(',')
            let picUrls = []
            for (let i = 0; i < list.length; i++) {
                let url = import.meta.env.VITE_API_URL + '/attachment/' + list[i]
                picUrls.push(url)
            }
            picUrls.value = picUrls
        }

        // 显示保存按钮条件
        let currentUser = localStorage.getItem('username')
        if (data.state == 0 && data.createBy === currentUser) {
            showSaveBtn.value = true
        } else {
            showSaveBtn.value = false
        }
        // 显示审批按钮条件
        if (data.state != 0 && data.handler === currentUser) {
            showReviewBtn.value = true
        } else {
            showReviewBtn.value = false
        }
        // 显示流程历史
        showFlowHis.value = true
    })
}

const onSubmit = () => {
    let params = form
    params['devices'] = JSON.stringify(params.deviceData)
    let processData = processRef.value.processList
    let allowSub = true
    for (let i = 0; i < processData.length; i++) {
        if (processData[i].handler == '') {
            allowSub = false
            break
        }
    }
    if (!allowSub) {
        ElNotification({
            title: '提示',
            message: '请选择审核人员',
            type: 'info'
        })
        return
    }
    params['flowList'] = processData
    http.fetchJson({
        url: '/yunying/deviceMaintain/save',
        data: params
    }).then((res) => {
        ElNotification({
            title: '提示',
            message: '保存成功',
            type: 'success'
        })
        closeWindow()
    })
}

const chooseDevice = () => {
    showDevice.value = true
}

const deviceSelected = (res) => {
    let list = form.deviceData
    for (let i = 0; i < res.length; i++) {
        let json = {
            id: res[i].id,
            code: res[i].code,
            name: res[i].name,
            model: res[i].model
        }
        list.push(json)
    }
    form.deviceData = list
    showDevice.value = false
}

const chooseProject = () => {
    showProjectGridCpt.value = true
}

const projectSelected = (res) => {
    console.log(res)
    let info = res[0]
    form.projectId = info.id
    form.projectCode = info.code
    form.projectName = info.name
    showProjectGridCpt.value = false
}

const onReview = () => {
    showReviewDialog.value = true
}

const closeReviewDialog = (refresh) => {
    showReviewDialog.value = false
    if (refresh) {
        loadDetail()
    }
}

const uploadPic = () => {
    fileInput.value.dispatchEvent(new MouseEvent('click'))
}

const onFileChange = () => {
    let fileObj = fileInput.value.files[0]
    if (fileObj) {
        let fd = new FormData()
        fd.append('file', fileObj)
        // 修改请求地址
        http.fetchFile({
            url: '/sys/file/upload',
            method: 'post',
            data: fd
        }).then((res) => {
            ElNotification({
                title: '提示',
                message: '上传成功',
                type: 'success'
            })
            let picsStr = form.pics
            let picUrls = picUrls.value
            if (picsStr != '') {
                picsStr = picsStr + ',' + res.data.storageName
            } else {
                picsStr = res.data.storageName
            }
            let url = import.meta.env.VITE_API_URL + '/attachment/' + res.data.storageName
            picUrls.push(url)
            form.pics = picsStr
            picUrls.value = picUrls
        })
    } else {
        return
    }
}

const previewFile = (url) => {
    window.open(url)
}

const onPrint = () => {
    showPrint.value = true
}

onMounted(() => {
    if (props.id != '') {
        loadDetail()
    } else {
        showSaveBtn.value = true
    }
})
</script>
<style scoped>
@import '@/assets/css/table-form.css';

.attachment-content {
    width: 100%;
    padding: 10px;
    display: flex;
}

.attachment-box {
    width: 100px;
    height: 100px;
    margin-right: 10px;
    background: #f9f9f9;
}

.attachment-class {
    width: 100%;
    height: 100%;
}
</style>
